using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using Common.Utilities;

namespace Workflows.Components
{
    /// <summary></summary>
    public class ComponentEditorManager
    {
        /// <summary></summary>
        private Dictionary<string,Type> _TypeEditors;

        /// <summary></summary>
        public Dictionary<string, Type> Editors
        {
            get
            {
                return this._TypeEditors;
            }
        }

        /// <summary></summary>
        public ComponentEditorManager()
        {
            this._TypeEditors = new Dictionary<string, Type>();
            string binFolderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            DirectoryInfo dirInfo=new DirectoryInfo(binFolderPath);
            FileInfo[] dllInfos = dirInfo.GetFiles("*.dll", SearchOption.TopDirectoryOnly);
            if(dllInfos !=null && dllInfos.Length>0)
            {
                foreach(FileInfo dll in dllInfos)
                {
                    if (dll.Name.ToLower().StartsWith("workflow"))
                    {
                        try
                        {
                            Assembly assembly = Assembly.LoadFile(dll.FullName);
                            Type[] types = assembly.GetTypes();
                            if (types != null && types.Length > 0)
                            {
                                foreach (Type type in types)
                                {
                                    if (type.GetInterface(typeof (IComponentEditor).Name) != null)
                                    {
                                        try
                                        {
                                            IComponentEditor editor = (IComponentEditor)Activator.CreateInstance(type);
                                            if (!this._TypeEditors.ContainsKey(editor.WorkflowComponentType.FullName))
                                            {
                                                this._TypeEditors.Add(editor.WorkflowComponentType.FullName, type);
                                            }
                                        }
                                        catch (Exception ex1)
                                        {
                                            // ExceptionHandler.HandlesException(ex1);
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex0)
                        {
                            ExceptionHandler.HandlesException(ex0);
                        }
                    }
                }
            }
        }
    }
}
